<?php

class MediaController extends BaseClass
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $title;	//Page Title
	public $layout = 'main';
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions' => array('index', 'add', 'delete', 'process'),
				'users' => $this->getAdmins(),
			),
			array('deny', // deny other user to perform actions
					'actions' => array('index', 'add', 'delete', 'process'),
					'users' => array('*'),
			),
		);
	}
	

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$pdf = explode('/',Yii::app()->request->pathInfo);
		
		$model = new Media();
		$model->unsetAttributes();

		if (isset($_REQUEST['Media']['type']) && !empty($_REQUEST['Media']['type']))
			$model->type = $_REQUEST['Media']['type'];
		
		 if (isset($pdf[2]) && !empty($pdf[2]) && $pdf[2] == 'pdf')
		 	$model->type=2;
		 
		 if(isset($_REQUEST	['Media']['name']) && !empty($_REQUEST['Media']['type']))
		 	$model->name=$_REQUEST['Media']['name'];
		 
		 
		$this->title = Yii::app()->name."-Media";
		$this->render('index',array(
			'model'=>$model,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionAdd()
	{
		$this->title = "Add Media";
		$model = new Media();
		
		if ( isset($_POST['Media']) && !empty($_POST['Media']) ){
			
			//$this->pr($_FILES);
			
			if ( isset($_FILES['Media']['name']['url']) && !empty($_FILES['Media']['name']['url']) ){
				
				$ext = $this->getExtension($_FILES['Media']['name']['url']);
				$valid_arr = array('jpg', 'jpeg', 'png', 'gif', 'pdf');
				
				if (in_array($ext,$valid_arr)){
				
					//$newName = $this->generateNewNameOfImage($_FILES['Media']['name']['url']);
					
					$newName = $_FILES['Media']['name']['url'];
					
					$model->url = $newName;
					$model->type = ($ext == 'pdf') ? 2 : 1;
					$model->name = $_FILES['Media']['name']['url'];		
					$model->created = date("Y-m-d H:i:s");
					
					if ($model->validate()){
						if ($model->save()){
							
							if ($model->type == 2){
								move_uploaded_file($_FILES['Media']['tmp_name']['url'], './pdf/'.$newName);
								@chmod('./images/', 0777);
							} else {
								move_uploaded_file($_FILES['Media']['tmp_name']['url'], './images/'.$newName);
								@chmod('./images/', 0777);
							}
							Yii::app()->user->setFlash('success', 'File is successfully added');
							$this->redirect(Yii::app()->getBaseUrl().'/admin/media');
						} else {
							Yii::app()->user->setFlash('error', 'Please add a valid File with different ');
							$this->redirect(Yii::app()->getBaseUrl().'/admin/media/add');
						}
					} else {
						Yii::app()->user->setFlash('error', 'File already exists, choose a different name');
						$this->redirect(Yii::app()->getBaseUrl().'/admin/media/add');
					}
				} else{
					Yii::app()->user->setFlash('error', 'Only jpg, jpeg, png, gif, pdf allowed');
					$this->redirect(Yii::app()->getBaseUrl().'/admin/media/add');
				}
				
				
			} else {
					Yii::app()->user->setFlash('error', 'Please add an File first');
					$this->redirect(Yii::app()->getBaseUrl().'/admin/media/add');
				}
			
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id,$name)
	{
		$ext = $this->getExtension($name);
		if ($ext == 'pdf')
			@unlink('./pdf/'.$name);
		else
			@unlink('./images/'.$name);
		
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : $_SERVER['HTTP_REFERER']);
	}

	
	public function actionProcess(){
		$model = new Cms();
		if($_POST['pageAction'] == 'delete')
		{
			$criteria = new CDbCriteria;
			$criteria->addInCondition('id',$_POST['contact']);
			
			if(Cms::model()->deleteAll($criteria)) {
				Yii::app()->user->setFlash('success','Record (s) Successfully Deleted');
				$this->redirect(Yii::app()->getBaseUrl().'/admin/cms');
			}
			else {
				Yii::app()->user->setFlash('error','Record (s) not Deleted');
				$this->redirect(Yii::app()->getBaseUrl().'/admin/cms');
			}
		}
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Cms the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Media::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Cms $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='cms-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
